#include <iostream>
#include <cstdio>
#include <string>
#include <mysql/mysql.h>
#include <unistd.h>

const std::string host = "127.0.0.1";
const std::string user = "sqy";
const std::string passwd = "suqianyang1111";
const std::string db = "test";
const unsigned int port = 8080;


int main()
{
    //printf("mysql client version:%s\n",mysql_get_client_info());
    MYSQL* my = mysql_init(nullptr);
    if(my == nullptr)
    {
        std::cerr << "init MYSQL error " << std::endl;
        exit(1);        
    }

    if(mysql_real_connect(my,host.c_str(),user.c_str(),passwd.c_str(),db.c_str(),port,nullptr,0) == nullptr)
    {
        std::cerr << "connect MYSQL error " << std::endl;
        exit(2);
    }

    mysql_set_character_set(my,"utf8");
    //std::string sql = "insert into users (name,age,telphone) values ('张三', 18,'123456789')";
    std::string sql = "select * from users";

    int n = mysql_query(my,sql.c_str());
    if(n == 0) std::cout << sql << " success " <<std::endl;
    else 
    {
        std::cerr << sql << " failed " << std::endl;
        exit(3);
    }

    MYSQL_RES * res = mysql_store_result(my);
    if(res == nullptr)
    {
        std::cerr << "mysql_store_result error " << std::endl;
        exit(4);
    }

    my_ulonglong row = mysql_num_rows(res);
    my_ulonglong col = mysql_num_fields(res);
    std::cout << "行: " << row << std::endl;
    std::cout << "列: " << col << std::endl;
    for(my_ulonglong i = 0; i < row; i++)
    {
        MYSQL_ROW rows = mysql_fetch_row(res);
        for(my_ulonglong j = 0; j < col; j++)
        {
            std::cout << rows[j] << "\t";
        }
        std::cout << std::endl;

    }

    //std::cout << "connect success" << std::endl;

    mysql_close(my);
    return 0;
}
